package com.app.piemoment;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.app.piemoment.api.ApiResult;
import com.app.piemoment.api.ApiReturnResultListener;
import com.app.piemoment.api.MatchApi;
import com.app.piemoment.config.Config;
import com.app.piemoment.entity.Address;
import com.app.piemoment.entity.MatchInfo;
import com.app.piemoment.entity.OppositeInfo;
import com.app.piemoment.image.ImageLoaderManager;
import com.app.piemoment.log.PMLog;
import com.app.piemoment.talk.TalkActivity;
import com.app.piemoment.util.StringUtils;
import com.app.piemoment.util.ToastManager;
import com.app.piemoment.view.MyDialog;

public class PairActivity extends BaseActivity implements OnTouchListener{
	private static final String TAG = "PairActivity";
	private RelativeLayout personal_item;
	private TextView username_text;
	private TextView personal_info;
	private TextView time_clock;
	private ImageView clock_image;
	private LinearLayout process_item;
	private LinearLayout btn_like;
	private LinearLayout btn_pass;
	
	private RelativeLayout mainLayout;
	private String mid;
	private MatchInfo current;
	private Timer timer;
	private boolean choose = true;
	private LinearLayout choose_item;
	private TextView choose_text;
	protected MatchInfo info;
	private Button btn_info;
	private Button btn_album;
	private Button btn_qa;
	private Button btn_location;
	private Button btn_msg;
	private Button btn_more;
	
	private static final int INTERVAL = 1*60*1000;//1分钟

	public PairActivity() {
		mainViewId = R.layout.pair_activity;
	}
	

	@Override
	protected void initMainView() {
		
		mainLayout = (RelativeLayout) findViewById(R.id.mainlayout);
		personal_item = (RelativeLayout) findViewById(R.id.personal_item);
		username_text = (TextView) findViewById(R.id.username);//王berry
		personal_info = (TextView) findViewById(R.id.personal_info);//1988/水瓶/北京
		time_clock = (TextView) findViewById(R.id.time_clock);//倒计时
		clock_image = (ImageView)findViewById(R.id.clock_image);
		choose_item = (LinearLayout)findViewById(R.id.choose_item);
		choose_text = (TextView)findViewById(R.id.choose_text);
		
		process_item = (LinearLayout)findViewById(R.id.process_item);
		btn_like = (LinearLayout) findViewById(R.id.btn_like);
		btn_pass = (LinearLayout) findViewById(R.id.btn_pass);
		
		choose_item.setVisibility(View.GONE);
		//menu
		btn_info = (Button)findViewById(R.id.btn_info);
		btn_album = (Button)findViewById(R.id.btn_album);
		btn_qa = (Button)findViewById(R.id.btn_qa);
		btn_location = (Button)findViewById(R.id.btn_location);
		btn_msg = (Button)findViewById(R.id.btn_msg);
		btn_more = (Button)findViewById(R.id.btn_more);
		
	}

	@Override
	protected void registerMainViewEvent() {
		btn_like.setOnClickListener(this);
		btn_pass.setOnClickListener(this);
		//menu
		btn_info.setOnTouchListener(this);
		btn_album.setOnTouchListener(this);
		btn_qa.setOnTouchListener(this);
		btn_location.setOnTouchListener(this);
		btn_msg.setOnTouchListener(this);
		btn_more.setOnTouchListener(this);
	}

	@Override
	protected void processMainView() {
		mid = getIntent().getStringExtra("mid");
		
		personal_item.getBackground().setAlpha(50);
		getMatch(mid);
	}
	
	private void updateUI(MatchInfo matchInfo) {
		current = matchInfo;
		mid = matchInfo.getMid()+"";
		PMLog.e(TAG, "mid is " + mid);
		OppositeInfo info = matchInfo.getTarget_info();
		if(info!=null) {
			super.updateTitle(info.getNickname());
			ImageLoaderManager imageloader = new ImageLoaderManager(this,new Handler());
			if(info.getPhotos()!=null) {
				mainLayout.setBackgroundDrawable(new BitmapDrawable(imageloader.getImage(Config.IMAGE_URL+info.getPhotos().get(0).getFilepath(), R.drawable.pm_default, 0)));
			}
			username_text.setText(info.getNickname());
			personal_info.setText(getBirthYear(info.getBirthday())+"/"+getCurrentAdd(info.getCurrentPlace()));
			
			if(timer!=null) {
				timer.cancel();
				timer = null;
			}
			timer = new Timer();
			timer.schedule(new TimerTask() {
				
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							Calendar cal = Calendar.getInstance();
							cal.set(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)+1, 11, 0, 0);
							long clock = cal.getTimeInMillis();
							long minuts = (clock-System.currentTimeMillis())/1000/60;
							int hour = (int) (minuts/60);
							int minut = (int) (minuts - 60*hour);
							clock_image.setVisibility(View.VISIBLE);
							time_clock.setText(hour +":" +minut);
							System.out.println(minuts);
							if(hour==0&&minut==0) {
								clock_image.setVisibility(View.GONE);
								time_clock.setText("已过期");
								choose = false;
								if(timer!=null) {
									timer.cancel();
									timer = null;
								}
							}
						}
					});
					
				}
			}, 0, INTERVAL);
		}
	}

	private String getBirthYear(String birthday) {
		//1985-01-01T00:00:00+0800
		if(!StringUtils.isNullOrEmpty(birthday)) {
			return birthday.substring(0, 4);	
		}
		return null;
	}


	private String getCurrentAdd(Address currentPlace) {
		if(currentPlace!=null) {
			return currentPlace.getArea();
		}
		return null;
	}

	private void getMatch(String mid) {
		MatchApi api = new MatchApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(LOAD_PROGRESS);
				if(ApiResult.RESULT_OK==apiResult.getResultCode()) {
					JSONObject jsonEntity = apiResult.getJsonEntity();
					Log.e("aa", jsonEntity.toString());
					try {
						if (jsonEntity != null) {
							if(jsonEntity.has("status")) {
								String result = jsonEntity.getString("status");
								if(ApiResult.Success.equals(result)) {
									if(jsonEntity.has("data")) {
										JSONObject json = jsonEntity.getJSONObject("data");
										if(json!=null) {
											info = new MatchInfo();
											info.parser(json);
										}
									}
									
									
								}
								updateUI(info);
							}
						
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(LOAD_PROGRESS);
				
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				dismissDialog(LOAD_PROGRESS);
			}
		});
		api.getMatchById(1, this, mid);
	}
	
	/**
	 * 配对成功或者失败 或者等待对方选择
 	 * @param type
	 */
	private void updateResult(int type) {
		process_item.removeAllViews();
		LinearLayout layout = new LinearLayout(this);
		LinearLayout.LayoutParams layoutLP = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
		LinearLayout.LayoutParams tLP = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
		tLP.gravity = Gravity.CENTER;
		TextView text = new TextView(this);
		text.setTextSize(20.f);
		text.setGravity(Gravity.CENTER);
		switch (type) {
		case 0:
			layout.setBackgroundColor(Color.parseColor("#846d63"));
			text.setText("等待对方选择");
			text.setTextColor(getResources().getColor(R.color.white));
			break;
		case 1:
			layout.setBackgroundColor(Color.parseColor("#f76d84"));
			text.setText("配对成功");
			text.setTextColor(getResources().getColor(R.color.white));
			break;
		case 2:
			layout.setBackgroundColor(Color.parseColor("#846d63"));
			text.setText("配对失败");
			text.setTextColor(getResources().getColor(R.color.white));
			break;

		default:
			break;
		}
		layout.addView(text,tLP);
		process_item.addView(layout,layoutLP);
	}
	
	@Override
	public void onClick(View v) {
		final MatchApi api = new MatchApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(LOAD_PROGRESS);
				if(ApiResult.RESULT_OK==apiResult.getResultCode()) {
					JSONObject jsonEntity = apiResult.getJsonEntity();
					Log.e("aa", jsonEntity.toString());
					try {
						if (jsonEntity != null) {
							if(jsonEntity.has("status")) {
								String result = jsonEntity.getString("status");
								if(ApiResult.Success.equals(result)) {
									ToastManager.showToast(PairActivity.this, "提交成功");
								}else {
									ToastManager.showToast(PairActivity.this, "提交失败");
								}
								updateResult(2);
							}
						
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
			}
			

			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(LOAD_PROGRESS);
				
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				dismissDialog(LOAD_PROGRESS);
				ToastManager.showToast(PairActivity.this, "提交失败");
				updateResult(2);
			}
		});
		
		switch (v.getId()) {
		case R.id.btn_left:
			super.onBackPressed();
			break;
		case R.id.btn_right:
			Intent intent = new Intent(this, PairDetailActivity.class);
			intent.putExtra("matchInfo", current);
			startActivity(intent);
			break;
		case R.id.btn_like:
			if(!choose) {
				ToastManager.showToast(this, "已经超过选择时间");
				return ;
			}
			new MyDialog(this,"喜欢","确定点Like吗？")
			.setPositiveButton(new MyDialog.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					api.likeById(1, PairActivity.this, mid);
				}
			})
			.setNegativeButton(new MyDialog.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Log.e("aa", "取消");
					dialog.dismiss();
				}
			})
			.show();
			
			break;
		case R.id.btn_pass:
			if(!choose) {
				ToastManager.showToast(this, "已经超过选择时间");
				return ;
			}
			
			new MyDialog(this,"不喜欢","确定点Pass吗？")
			.setPositiveButton(new MyDialog.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					api.passById(1, PairActivity.this, mid);
				}
			})
			.setNegativeButton(new MyDialog.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Log.e("aa", "取消");
					dialog.dismiss();
				}
			})
			.show();
			break;
		default:
			break;
		}
	}
	
	private void processButton() {
		((LinearLayout)btn_info.getParent()).setBackgroundResource(R.drawable.match_normal);
		((LinearLayout)btn_album.getParent()).setBackgroundResource(R.drawable.match_normal);
		((LinearLayout)btn_qa.getParent()).setBackgroundResource(R.drawable.match_normal);
		((LinearLayout)btn_location.getParent()).setBackgroundResource(R.drawable.match_normal);
		((LinearLayout)btn_msg.getParent()).setBackgroundResource(R.drawable.match_normal);
		((LinearLayout)btn_more.getParent()).setBackgroundResource(R.drawable.match_normal);
	}


	/* Creates the menu items */
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "心理测试");
		menu.add(0, 1, 0, "问答");
		return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			Intent test = new Intent(this, ModuleActivity.class);
			startActivity(test);
			break;
		case 1:
			Intent qaIntent = new Intent(this, QAActivity.class);
			startActivity(qaIntent);
			break;
		}
		return false;
	}


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		Intent intent = null;
		if(MotionEvent.ACTION_DOWN==event.getAction()) {
			switch (v.getId()) {
			case R.id.btn_info:
				processButton();
				((LinearLayout)btn_info.getParent()).setBackgroundResource(R.drawable.match_click);
				break;
			case R.id.btn_album:
				processButton();
				((LinearLayout)btn_album.getParent()).setBackgroundResource(R.drawable.match_click);
				break;
			case R.id.btn_qa:
				processButton();
				((LinearLayout)btn_qa.getParent()).setBackgroundResource(R.drawable.match_click);
				break;
			case R.id.btn_location:
				processButton();
				((LinearLayout)btn_location.getParent()).setBackgroundResource(R.drawable.match_click);
				break;
			case R.id.btn_msg:
				processButton();
				((LinearLayout)btn_msg.getParent()).setBackgroundResource(R.drawable.match_click);
				break;
			case R.id.btn_more:
				processButton();
				((LinearLayout)btn_more.getParent()).setBackgroundResource(R.drawable.match_click);
				break;
				
			default:
				break;
			}
		}else if(MotionEvent.ACTION_UP==event.getAction()) {
			switch (v.getId()) {
			case R.id.btn_info:
				processButton();
				((LinearLayout)btn_info.getParent()).setBackgroundResource(R.drawable.match_normal);
				intent = new Intent(this,PairDetailActivity.class);
				intent.putExtra("matchInfo", info!=null?info.getTarget_info():null);
				startActivity(intent);
				break;
			case R.id.btn_album:
				processButton();
				((LinearLayout)btn_album.getParent()).setBackgroundResource(R.drawable.match_normal);
				if(info!=null) {
					OppositeInfo target_info = info.getTarget_info();
					if(target_info!=null&&target_info.getPhotos()!=null) {
						intent = new Intent(this,AlbumActivity.class);
						intent.putExtra("photo", target_info);
						startActivity(intent);
					}else {
						ToastManager.showToast(this, "没有照片可以查看");
					}
				}
				break;
			case R.id.btn_qa:
				processButton();
				((LinearLayout)btn_qa.getParent()).setBackgroundResource(R.drawable.match_normal);
				intent = new Intent(this,QAActivity.class);
				intent.putExtra("mid", info!=null?info.getMid()+"":"");
				intent.putExtra("oppname", info!=null?info.getTarget_info().getNickname():"");
				startActivity(intent);
				break;
			case R.id.btn_location:
				processButton();
				((LinearLayout)btn_location.getParent()).setBackgroundResource(R.drawable.match_normal);
				intent = new Intent(this,LocationActivity.class);
				startActivity(intent);
				break;
			case R.id.btn_msg:
				processButton();
				((LinearLayout)btn_msg.getParent()).setBackgroundResource(R.drawable.match_normal);
				intent = new Intent(this,TalkActivity.class);
				startActivity(intent);
				break;
			case R.id.btn_more:
				processButton();
				((LinearLayout)btn_more.getParent()).setBackgroundResource(R.drawable.match_normal);
				super.onBackPressed();
				break;
				
			default:
				break;
			}
		}
		return false;
	}


}
